<?php
/**
 * 订单的自动审核
 *
 * @author liugang<liugang@shopex.cn>
 * @version $2017-3-09 11:03Z
 */
$domain = $argv[1];

if (empty($domain)) {
    die('No Params');
}

set_time_limit(0);

require_once(dirname(__FILE__) . '/../../lib/init.php');

cachemgr::init(false);

$_SERVER['HTTP_HOST'] = $domain;

$now = time();
$begintime = date("m-d H:i");
$limit1_time = $now -1800;
// $limit1_time = $now;
$limit2_time = $now -86400;
$oOrders = app::get('ome')->model('orders');
$oOrderItemMdl = app::get('ome')->model('order_items');
$oOrdersObjMdl = app::get('ome')->model('order_objects');
$orderReplace=kernel::single('ome_order_replace');
$order_list = $oOrders->getlist('pay_status,order_id,is_replace,shop_id,is_cod,status,order_bn,service_price,cost_freight',array('order_confirm_filter' => '(op_id IS NULL AND group_id IS NULL AND (is_cod=\'true\' or pay_status in (\'1\',\'4\',\'5\')))', 'status' => 'active', 'ship_status' => '0','download_time|lthan'=>$limit1_time,'download_time|than'=>$limit2_time, 'f_ship_status' => '0', 'confirm' => 'N', 'abnormal' => 'false', 'is_auto' => 'false', 'is_fail' => 'false'));
//error_log(var_export($order_list,true)."\n\t",3,PUBLIC_DIR."/order_list2333333222.log");



//error_log(var_export($order_list,true)."\n\t",3,PUBLIC_DIR."/order_list2333333222.log");
if(empty($order_list)) return false;
foreach ($order_list as $k => $v)
{
    //只有没有替换的订单  才进行替换
    if($v['is_replace']=='false'){
        try{
            //先获取数据   $sdf a
            // 获取该所有订单明细
            $orderItems = $oOrderItemMdl ->getlist('*',array('order_id'=>$v['order_id'],'delete'=>'false'));
            $items_data=array();
            $pre_datas=array();
            foreach($orderItems as $item) 
            {
                $items_data[$item['item_id']]['rep_bm_id'] = $item['product_id'];
                $items_data[$item['item_id']]['rep_material_bn'] = $item['bn'];
                $items_data[$item['item_id']]['repalce_num'] = $item['nums'];
                $items_data[$item['item_id']]['ti_num'] = $item['nums'];
                $items_data[$item['item_id']]['rep_material_name'] = $item['name'];
                $items_data[$item['item_id']]['item_id'] = $item['item_id'];
                $items_data[$item['item_id']]['obj_id'] = $item['obj_id'];
                $items_data[$item['item_id']]['price'] = $item['price'];
                $items_data[$item['item_id']]['pmt_price'] = $item['pmt_price'] / $item['nums'];
                $items_data[$item['item_id']]['part_mjz_discount'] = $item['part_mjz_discount'] / $item['nums'];

                $pre_datas[$item['product_id']]['nums'] = $item['nums'];
                $pre_datas[$item['product_id']]['item_id'] = $item['item_id'];
                $pre_datas[$item['product_id']]['obj_id'] = $item['obj_id'];
            }

            //获取该订单  最终所替代的明细   比对之前的明细  再进行处理
            $data=$orderReplace->dealdata($items_data,$v['shop_id']);
            $data2=array();
            foreach($data as $kk=>$vv)
            {
                //说明替换物料有原物料中的一种  在
                if($pre_datas[$vv['rep_bm_id']])
                {
                    //如果 最终明细有一个原物料  且数量相同 则说明改 明细不用修改状态  改最终物料不需要重新插入
                    if($vv['repalce_num']==$pre_datas[$vv['rep_bm_id']]['nums'])
                    { 
                        //add by ldward 20180830 如果替换后的物料同原明细有相同切数量相同，则累加数量、实付金额、销售价格
                        if(empty($vv['item_id']))
                        {
                            //如果item_id为空，则是替代物料，替代物料为原物料切且数量相同，一样添加到明细中
                            
                            $data2[]=$vv;
                        }
                        $pre_datas[$vv['rep_bm_id']]['is_replace']='false';
                        continue;
                    }else{
                        //有原物料  但是数据不一致  该最终明细 可以插入新的明细
                        $data2[]=$vv;
                    }
                }else{
                    //最终物料  在原物料没有  则说明  是替换的 可以插入新的明细
                    $data2[]=$vv;
                }
            }

            //如果新插入的  数组 为空  说明该订单不需要替换
            if(!empty($data2))
            {

                //add by ldward 因过数价格取价异常，则修改源头，如果存在相同料品（普通+普通、普通+促销），则进行平均
                
                error_log(date('Y-m-d H:i:s').'['.$v['order_id'].']'.var_export($data2, true), 3, PUBLIC_DIR.'/autoreplace'.date('Y-m-d').'.log');
                //                    var_dump($data2);die;
                //循环插入新数组
                kernel::database()->beginTransaction();
                $res1=false;
                $res2=false;
                foreach($data2 as $newk=>$newv){
                    $orderReplace->createObjectItems_new($newv,$v['order_id']);
                    $res1=true;
                }
                //循环修改 原来订单明细的状态
                foreach($pre_datas as $key2 =>$vlaue2){
                    if($vlaue2['is_replace']=='false') continue;
                    $oOrderItemMdl = app::get('ome')->model('order_items');
                    $oOrdersObjMdl = app::get('ome')->model('order_objects');
                    $oOrderItemMdl ->update(array('delete'=>'true'),array('item_id' => $vlaue2['item_id']));
                    $oOrdersObjMdl ->update(array('delete'=>'true'),array('obj_id' => $vlaue2['obj_id']));
                    $oOrders ->update(array('is_replace'=>'true','replaced'=>'true'),array('order_id' => $v['order_id']));
                    //$orderItems_rep = $oOrderItemMdl ->getlist('*',array('item_id'=>$vlaue2['item_id']));
                    //$itemRepMdl = app::get('ome')->model('order_itemsRep');
                    //$itemRepMdl->save($orderItems_rep[0]);
                    $res2=true;
                }
                if($res1 && $res2){
                    kernel::database()->commit();
                }else{
                    kernel::database()->rollback();
                }
            }

            // #记录操作日志
            // $oOperation_log = app::get('ome')->model('operation_log');
            // $oOperation_log->write_log('order_edit@ome',$data['order_id'],"订单物料".$material."手动替换为".$material_replace);


            //查询是否有相同的物料行
            //add by ldward 因过数价格取价异常，则修改源头，如果存在相同料品（普通+普通、普通+促销），则进行平均
            $db=kernel::database();
            $sql="SELECT * from (
                        select order_id,bn,ROUND(sum(divide_order_fee)/sum(nums),4) divide_order_fee,count(bn) _c
                        from sdb_ome_order_items where order_id=".$v['order_id']." and `delete`='false' group by order_id,bn
                        )t where t._c>1";
            $recopydata = $db->select($sql);
            if(!empty($recopydata))
            {
                foreach ($recopydata as $key => $value) 
                {
                    $db->exec("update sdb_ome_order_items set divide_order_fee=nums*".$value['divide_order_fee']." where order_id=".$v['order_id']." and bn='".$value['bn']."'");   
                }
            }
            //add by ldward 20181114 添加过滤赠品
            if ($v['service_price']>0 || $v['cost_freight']>0){
                kernel::single('ome_order_edit')->updateItemObj($v['order_bn']);
            }else{
                kernel::single("ome_order_fail")->modifyOrderDividefee($v['order_id']);
            }
            
            

        }catch (Exception $e){
            kernel::database()->rollback();
            $msg=$e->getMessage();
            error_log(var_export(date('Y-m-d H:i:s') . 'replace-----' . $msg,true)."\n\t",3,PUBLIC_DIR."/replace_" . date('Y-m-d').".log");
            //如果报错 回滚
            continue;
        }
    }

    //error_log(var_export(222222,true)."\n\t",3,PUBLIC_DIR."/323333333333333.log");
    if(($v['pay_status'] == '1' || $v['is_cod'] == 'true') && $v['status'] == 'active')
    {
        $result = kernel::single('ome_order')->auto_order_combine($v['order_id']);
        error_log(var_export($v['order_id'],true)."\n\t",3,PUBLIC_DIR."/order_id_" . date('Y-m-d').".log");
    }

}









